package com.ruoyi.informfrontend.controller;

import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.informfrontend.domain.Register;
import com.ruoyi.informfrontend.domain.SysUser;
import com.ruoyi.informfrontend.mapper.SysUserMapper;
import com.ruoyi.informfrontend.service.ISysUserService;
import com.ruoyi.informfrontend.tool.SendTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 用户Controller
 *
 * @author ruoyi
 * @date 2023-05-17
 */
@RestController
@RequestMapping("/user")
public class SysUserController extends BaseController {
    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SendTool sendTool;

    @Autowired
    private RedisService redis;


    /**
     * 获取注册短信验证码
     */
    @GetMapping("/getCode")
    private AjaxResult getCode(@RequestParam String phone) throws Exception {
        SysUser user = sysUserService.selectSysUserByPhone(phone);
        if (user != null) {
            return error("用户已存在");
        }
        String code = sendTool.sendSms(phone, 1);
//        String code = creatCode(6);
        redis.setCacheObject("code:" + phone, code, 30L, TimeUnit.MINUTES);
        return success("发送成功");
    }


    @GetMapping("/allCode")
    private AjaxResult getAllCode(@RequestParam String phone, @RequestParam Integer type) throws Exception {
        /*type 0登录 1注册 2修改 3微信绑定*/
//        String code = creatCode(6);
        if (type == 1 || type == 3) {
            SysUser user = sysUserService.selectSysUserByPhone(phone);
            if (user != null) {
                return error("用户已存在");
            }

            if (type == 1) {
                String code = sendTool.sendSms(phone, 1);
                redis.setCacheObject("code:" + phone, code, 30L, TimeUnit.MINUTES);
                return success("发送成功");
            } else {
                String code = sendTool.sendSms(phone, 2);
                redis.setCacheObject("weixinCode:" + phone, code, 30L, TimeUnit.MINUTES);
                return success("发送成功");
            }
        } else {
            SysUser user = sysUserService.selectSysUserByPhone(phone);

            if (user == null) {
                return error("用户不存在");
            }
            if (type == 0) {
                String code = sendTool.sendSms(phone, 0);
                redis.setCacheObject("loginCode:" + phone, code, 30L, TimeUnit.MINUTES);
                return success("发送成功");
            } else if (type == 2) {
                String code = sendTool.sendSms(phone, 2);
                redis.setCacheObject("changeCode:" + phone, code, 30L, TimeUnit.MINUTES);
                return success("发送成功");
            } else {
                return error("此类型验证码不存在");
            }
        }
    }

    /**
     * 获取修改密码短信验证码
     */
    @GetMapping("/getChangeCode")
    private AjaxResult getCode2(@RequestParam String phone) throws Exception {
        SysUser user = sysUserService.selectSysUserByPhone(phone);
        if (user == null) {
            return error("用户不存在");
        }
        String code = sendTool.sendSms(phone, 2);
//        String code = creatCode(6);
        redis.setCacheObject("changeCode:" + phone, code, 30L, TimeUnit.MINUTES);
        return success("发送成功");
    }

    /**
     * 获取登录短信验证码
     */
    @GetMapping("/getLoginCode")
    private AjaxResult getCode3(@RequestParam String phone) throws Exception {
        SysUser user = sysUserService.selectSysUserByPhone(phone);
        if (user == null) {
            return error("用户不存在");
        }
        String code = sendTool.sendSms(phone, 1);
//        String code = creatCode(6);
        redis.setCacheObject("loginCode:" + phone, code, 30L, TimeUnit.MINUTES);
        return success("发送成功");
    }


    /**
     * 登陆后修改密码
     */
    @PutMapping("/updatePassword")
    public AjaxResult updatePassword(@RequestParam("phone") String phone
            , @RequestParam("code") String code
            , @RequestParam("password") String password) {

        SysUser user = sysUserService.selectSysUserByUserId(SecurityUtils.getUserId());
        if (user != null) {
            if (phone.equals(user.getPhonenumber())) {
                String codes = redis.getCacheObject("changeCode:" + phone);
                if (codes != null) {
                    if (code.equals(codes)) {
                        /*修改密码*/
                        SysUser sysUser = new SysUser();
                        sysUser.setUserId(SecurityUtils.getUserId());
                        sysUser.setPassword(SecurityUtils.encryptPassword(password));
                        return toAjax(sysUserService.updateSysUser(sysUser));
                    } else {
                        return AjaxResult.error("验证码不正确");
                    }
                } else {
                    return AjaxResult.error("验证码已过期，请重新获取");
                }
            } else {
                return AjaxResult.error("手机号与当前账号不一致");
            }
        } else {
            return AjaxResult.error("用户不存在");
        }
    }

    /**
     * 未登录修改密码
     */
    @PutMapping("/forgetPassword")
    public AjaxResult forgetPassword(@RequestParam("phone") String phone
            , @RequestParam("code") String code
            , @RequestParam("password") String password) {

        SysUser user = sysUserService.selectSysUserByPhone(phone);
        if (user != null) {
            String codes = redis.getCacheObject("changeCode:" + phone);
            if (codes != null) {
                if (code.equals(codes)) {
                    /*修改密码*/
                    SysUser sysUser = new SysUser();
                    sysUser.setUserName(phone);
                    sysUser.setPassword(SecurityUtils.encryptPassword(password));
                    return toAjax(sysUserService.updateSysUserByPhone(sysUser));
                } else {
                    return AjaxResult.error("验证码不正确");
                }
            } else {
                return AjaxResult.error("验证码已过期，请重新获取");
            }

        } else {
            return AjaxResult.error("用户不存在");
        }
    }


    /**
     * 微信登录绑定手机号
     */
    @PutMapping("/updatePhone")
    public AjaxResult updatePhone(@RequestParam("phone") String phone
            , @RequestParam("code") String code, @RequestParam("password") String password) {

        SysUser user = sysUserService.selectSysUserByPhone(phone);

        if (user == null) {
            String codes = redis.getCacheObject("weixinCode:" + phone);
            if (codes != null) {
                if (code.equals(codes)) {
                    /*修改手机号*/
                    SysUser sysUser = new SysUser();
                    sysUser.setUserId(SecurityUtils.getUserId());
                    sysUser.setUserName(phone);
                    sysUser.setPhonenumber(phone);
                    sysUser.setPassword(SecurityUtils.encryptPassword(password));
                    return toAjax(sysUserService.updateSysUser(sysUser));
                } else {
                    return AjaxResult.error("验证码不正确");
                }
            } else {
                return AjaxResult.error("验证码已过期，请重新获取");
            }
        } else {
            return AjaxResult.error("用户已存在");
        }
    }


    /**
     * 查询用户列表
     */
    @GetMapping("/list")
    public TableDataInfo list(SysUser sysUser) {
        startPage();
        List<SysUser> list = sysUserService.selectSysUserList(sysUser);
        return getDataTable(list);
    }


    /**
     * 获取用户详细信息
     */
    @GetMapping(value = "/getOne")
    public AjaxResult getInfo(@RequestParam(value = "userId", defaultValue = "0") Long userId) {
        if (userId == 0) {
            userId = SecurityUtils.getUserId();
        }
        return success(sysUserService.selectSysUserByUserId(userId));
    }

//    /**
//     * 新增用户
//     */
//    @PostMapping
//    public AjaxResult add(@RequestBody SysUser sysUser) {
//        return toAjax(sysUserService.insertSysUser(sysUser));
//    }

    /**
     * 注册用户
     */
    @PostMapping("/register")
    public AjaxResult add(@RequestBody Register register) {
        SysUser sysUser = new SysUser();
        sysUser.setPhonenumber(register.getPhone());

        /*校验手机号*/
        if (sysUserMapper.checkPhoneNumber(sysUser) == 0) {
            /*校验验证码*/
            String codes = redis.getCacheObject("code:" + register.getPhone());
            String code = register.getCode();
            if (codes != null) {
                if (code.equals(codes)) {
                    sysUser.setUserType(register.getUserType());
                    sysUser.setPassword(SecurityUtils.encryptPassword(register.getPassword()));
                    return AjaxResult.success(sysUserService.insertSysUser(sysUser));

                } else {
                    return AjaxResult.error("验证码不正确");
                }
            } else {
                return AjaxResult.error("验证码已过期，请重新获取");
            }
        } else {
            return error("手机号已存在");
        }


    }


    /**
     * 修改用户
     */
    @PutMapping
    public AjaxResult edit(@RequestBody SysUser sysUser) {
        return toAjax(sysUserService.updateSysUser(sysUser));
    }

    /**
     * 删除用户
     */
    @DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds) {
        return toAjax(sysUserService.deleteSysUserByUserIds(userIds));
    }

    public static String creatCode(int n) {
        //3、定义一个字符串变量记录生成的随机字符
        String code = "";
        Random r = new Random();
        //2、定义一个for循环，循环n次，依次生成随机字符
        for (int i = 0; i < n; i++) {
            //i=0 1 2
            //3、生成一个随机字符，英文大、小写 数字（0 1 2 ）
//            int type = r.nextInt(3);//0 1 2
            int type = 2;
            switch (type) {
                case 0:
                    //大写字符（A 65-Z 65+25）
                    char ch = (char) (r.nextInt(26) + 65);
                    code += ch;
                    break;
                case 1:
                    //小写字符（a 97-z 97+25）
                    char ch1 = (char) (r.nextInt(26) + 97);
                    code += ch1;
                    break;
                case 2:
                    //数字字符
                    code += r.nextInt(10);//0-9
                    break;
            }
        }
        return code;
    }
}
